const Router = require('koa-router')
const {UserModel} = require('../../model/userModel')
const {TokenValidator, NotEmptyValidator} = require('../../validators/token')
const {LoginType} = require('../../lib/enum')
const {generateToken} = require('../../../core/util')
const {Auth} = require('../../../middlewares/auth')
const {WXManager} = require('../../service/wx')
const router = new Router({
  prefix: '/v1/token'
})

/**
 * @params {account、secret、type}
 */
// 获取 token
router.post('/', async (ctx) => {
  const v = await new TokenValidator().validate(ctx)
  // 业务分层
  // 1.在API接口编写
  // 2.Model 分层
  // MVC Model

  // 业务分层
  // Model DTO

  let token = ''
  switch (v.get('body.type')) {
    // email登录
      case LoginType.USER_EMAIL:
          /**
           * account代表邮箱
           * secret代表密码
           */
          token = await emailLogin(v.get('body.account'), v.get('body.secret'))
          break;

      // 小程序登录
      case LoginType.USER_MINI_PROGRAM:
          /**
           * account代表微信code
           */
          token = await WXManager.codeToToken(v.get('body.account'))
          break;

      // 管理员登录
      case LoginType.ADMIN_EMAIL:
          break;

      default:
          throw new global.errs.ParameterException('没有相应的处理函数')
  }
  ctx.body = {
    token
  }
})

// 验证token
router.post('/verify', async (ctx) => {
  const v = await new NotEmptyValidator().validate(ctx)
  const result = Auth.verifyToken(v.get('body.token'))

  ctx.body = {
      isValid: result
  }
})

async function emailLogin(account, secret) {
  const user = await UserModel.verifyEmailPassword(account, secret)

  // 发布令牌 第二个是权限机制
  console.log(Auth.USER)
  return generateToken(user.id, Auth.USER)
}

module.exports = router